﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Xsl;
using System.Xml;
using WSPDocumentBuilder_WPF.BLL;
using System.IO;

namespace WSPDocumentBuilder_WPF.Managers
{
    public static class XslManager
    {
        public static void GenerateXml(WSPDocumentationInfo docInfo)
        {
            // Création de la documentation xml
            string manifestXslPath = LocationManager.XslPath + @"\manifest.xslt";
            Transform(docInfo.ManifestPath, manifestXslPath, docInfo.XmlFilePath);
        }

        public static void GenerateExcelXml(WSPDocumentationInfo docInfo)
        {
            // Création de la documentation xml
            string excelXmlXslPath = LocationManager.XslPath + @"\wsp.xslt";
            Transform(docInfo.XmlFilePath, excelXmlXslPath, docInfo.ExcelXmlFilePath);
        }

        public static void GenerateExcelXml(string xmlSourceFilePath, string excelXmlFilePath)
        {
            // Création de la documentation xml
            string excelXmlXslPath = LocationManager.XslPath + @"\wsp.xslt";
            Transform(xmlSourceFilePath, excelXmlXslPath, excelXmlFilePath);
        }

        public static void ReplaceSPResourceTokens(string xmlSourceFilePath, string xmlDestFilePath)
        {
            string tokensXslPath = LocationManager.XslPath + @"\PostGen_ResolveTokens.xslt";
            Transform(xmlSourceFilePath, tokensXslPath, xmlDestFilePath);
        }

        private static void Transform(string inputFilePath, string xslFilePath, string outputFilePath)
        {
            // On permet les fonctions xsl ainsi que la résolution de documents externes
            XsltSettings settings = new XsltSettings()
            {
                EnableScript = true,
                EnableDocumentFunction = true
            };

            // On permet la résolution de feuille de transformations incluses
            DocInfoXslPathUrlResolver xslPathResolver = new DocInfoXslPathUrlResolver();

            // On permet la résolution de fichiers ouverts par la fonction xsl document()
            DocInfoDocumentPathUrlResolver documentPathResolver = new DocInfoDocumentPathUrlResolver(  System.IO.Path.GetDirectoryName(inputFilePath)  );

            // On charge la transformation
            XslCompiledTransform transformer = new XslCompiledTransform();
            transformer.Load(xslFilePath, settings, xslPathResolver);

            // On lance la transformation
            //ref : http://msdn.microsoft.com/en-US/library/ms163443(v=vs.100).aspx
            using (XmlReader reader = XmlReader.Create(inputFilePath))
            {
                using (XmlWriter writer = XmlWriter.Create(outputFilePath))
                {
                    transformer.Transform(reader, null, writer, documentPathResolver);
                }
            }
        }
    }
}
